#!/usr/bin/env node

const http = require('http'),
      fs = require('fs'),
      datalist = require('./data.js'),
      url = require('url');

function getData(){
  let datalist2 = datalist.filter((item)=>{
    return item.movieRange !== '暂无评分';
  });
  datalist2.sort((a,b)=>{
    return b.movieRange-a.movieRange;
  });
  console.log(datalist2);
  return datalist2;
}

function getPage(){
  let html = fs.readFileSync('./index.html').toString('utf8');
  return html;
}

http.createServer((req,res)=>{
  let addr = url.parse(req.url);
  let data = JSON.stringify(getData());
  if(addr.pathname === '/getlist'){
    res.writeHead(200,{
      'Content-Type':'application/json',
      'Content-length':Buffer.byteLength(data)
    });
    res.end(data);
  }
  else if(addr.pathname === '/'){
    res.writeHead(200,{
      'Content-Type':'text/html',
      'Content-length':Buffer.byteLength(getPage())
    });
    res.end(getPage());
  }
  else if(addr.pathname !== '/'){
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found!</h1>');
    return;
  }
}).listen(8080);
